package com.huhao.wshare.Dynamic;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;

import com.bumptech.glide.Glide;
import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.huhao.wshare.Config.DYNAMIC_API;
import static com.huhao.wshare.Config.FILE_UPLOAD_API;
import static com.huhao.wshare.Config.RELEASE_DYNAMIC_API;

public class ReleaseDynamicActivity extends BaseActivity implements ZoomedImageAdapter.OnImageCloseListener {
    private GridLayout imageContainer;
    private ImageButton btnAddPhoto;
    private final ArrayList<Uri> selectedImages = new ArrayList<>(9);
    private RecyclerView rvZoomedImages;
    private List<String> currentImageUrls = new ArrayList<>();
    private OkHttpClient client = new OkHttpClient();
    private List<String> uploadedImageUrls = new ArrayList<>(); // 存储上传成功的图片URL
    private int uploadCompletedCount = 0; // 上传完成计数
    private EditText etContent;
    // 存储图片Uri与进度条的映射关系
    private final Map<Uri, ProgressBar> imageProgressMap = new HashMap<>();

    // 权限相关组件
    private final ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(
            new ActivityResultContracts.RequestPermission(),
            isGranted -> {
                if (isGranted) {
                    openImagePicker();
                } else {
                    Toast.makeText(this, "需要存储权限访问相册", Toast.LENGTH_SHORT).show();
                }
            });

    // 图片选择回调
    private final ActivityResultLauncher<Intent> imagePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    handleImageSelection(result.getData());
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_dynamics);

        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(30, TimeUnit.SECONDS)     // 读取超时
                .writeTimeout(60, TimeUnit.SECONDS)    // 写入超时（上传大文件需要更长时间）
                .build();

        imageContainer = findViewById(R.id.image_container);
        ImageButton btnClose = findViewById(R.id.btn_close);
        btnAddPhoto = findViewById(R.id.btn_add_photo);
        Button btnPost = findViewById(R.id.btn_post);
        etContent = findViewById(R.id.et_content);

        // 初始化图片查看器RecyclerView
        rvZoomedImages = findViewById(R.id.rvZoomedImages);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvZoomedImages.setLayoutManager(layoutManager);
        rvZoomedImages.setVisibility(View.GONE);

        // 添加 PagerSnapHelper 确保滑动对齐
        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(rvZoomedImages);

        btnClose.setOnClickListener(v -> finish());
        btnAddPhoto.setOnClickListener(v -> checkPermissionAndOpenPicker());
        btnPost.setOnClickListener(v -> postDynamic());

        // 点击空白区域关闭图片查看器
        rvZoomedImages.setOnClickListener(v -> onImageClose());
    }

    private void checkPermissionAndOpenPicker() {
        // 根据系统版本选择需要请求的权限
        String requiredPermission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
            requiredPermission = Manifest.permission.READ_MEDIA_IMAGES;
        } else { // Android 12及以下
            requiredPermission = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        if (ContextCompat.checkSelfPermission(this, requiredPermission)
                == PackageManager.PERMISSION_GRANTED) {
            openImagePicker();
        } else {
            requestPermissionLauncher.launch(requiredPermission);
        }
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        imagePickerLauncher.launch(intent);
    }

    private void handleImageSelection(Intent data) {
        int remainingSlots = 9 - selectedImages.size();
        if (data.getClipData() != null) {
            int itemCount = data.getClipData().getItemCount();
            int addCount = Math.min(itemCount, remainingSlots);
            for (int i = 0; i < addCount; i++) {
                Uri imageUri = data.getClipData().getItemAt(i).getUri();
                selectedImages.add(imageUri);
                addImageToContainer(imageUri);
            }
        } else if (data.getData() != null) {
            Uri imageUri = data.getData();
            if (remainingSlots > 0) {
                selectedImages.add(imageUri);
                addImageToContainer(imageUri);
            }
        }
        updateAddButtonVisibility();
    }

    private void addImageToContainer(Uri uri) {
        // 创建FrameLayout容器用于叠加图片和进度条
        FrameLayout container = new FrameLayout(this);
        int imageSize = dpToPx(116);
        GridLayout.LayoutParams containerParams = new GridLayout.LayoutParams();
        containerParams.width = imageSize;
        containerParams.height = imageSize;
        containerParams.setMargins(dpToPx(8), dpToPx(8), dpToPx(8), dpToPx(8));
        container.setLayoutParams(containerParams);

        // 创建图片按钮
        ImageButton imageView = new ImageButton(this);
        FrameLayout.LayoutParams imageParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        imageView.setLayoutParams(imageParams);
        imageView.setScaleType(ImageButton.ScaleType.CENTER_CROP);
        imageView.setBackgroundColor(android.graphics.Color.TRANSPARENT);

        // 创建圆形进度条
        ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleSmall);
        FrameLayout.LayoutParams progressParams = new FrameLayout.LayoutParams(
                dpToPx(40), dpToPx(40));
        progressParams.gravity = Gravity.CENTER;
        progressBar.setLayoutParams(progressParams);
        progressBar.setVisibility(View.GONE); // 默认隐藏
        progressBar.setIndeterminate(true); // 不确定模式的圆形进度条

        // 将图片和进度条添加到容器
        container.addView(imageView);
        container.addView(progressBar);

        // 加载图片
        Glide.with(this)
                .load(uri)
                .centerCrop()
                .override(imageSize, imageSize)
                .into(imageView);

        // 将容器添加到网格布局（添加按钮前）
        imageContainer.addView(container, imageContainer.getChildCount() - 1);

        // 存储Uri与进度条的映射关系
        imageProgressMap.put(uri, progressBar);

        // 添加图片点击事件 - 打开图片查看器
        final int position = selectedImages.indexOf(uri);
        imageView.setOnClickListener(v -> openImageViewer(position));

        // 添加长按删除功能
        imageView.setOnLongClickListener(v -> {
            // 振动提示
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(200);
            }
            showDeleteConfirmationDialog(uri, container); // 传入容器视图
            return true;
        });
    }

    private void showDeleteConfirmationDialog(Uri uri, FrameLayout container) {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("删除图片")
                .setMessage("确定要删除这张图片吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    deleteImage(uri, container);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteImage(Uri uri, FrameLayout container) {
        // 从数据源中移除图片
        selectedImages.remove(uri);

        // 从界面中移除容器视图
        imageContainer.removeView(container);

        // 从映射中移除进度条
        imageProgressMap.remove(uri);

        // 更新添加按钮的可见性
        updateAddButtonVisibility();

        // 显示删除成功提示
        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
    }

    private void updateAddButtonVisibility() {
        btnAddPhoto.setVisibility(selectedImages.size() < 9 ? View.VISIBLE : View.GONE);
    }

    private void openImageViewer(int position) {
        // 将Uri转换为字符串列表传递给查看器
        currentImageUrls.clear();
        for (Uri uri : selectedImages) {
            currentImageUrls.add(uri.toString());
        }

        // 设置适配器并显示
        rvZoomedImages.setAdapter(new ZoomedImageAdapter(this, currentImageUrls, this));
        if (rvZoomedImages.getLayoutManager() instanceof LinearLayoutManager) {
            ((LinearLayoutManager) rvZoomedImages.getLayoutManager()).scrollToPositionWithOffset(position, 0);
        }
        rvZoomedImages.setVisibility(View.VISIBLE);
    }

    private void postDynamic() {
        String textContent = etContent.getText().toString().trim();

        if (textContent.isEmpty() && selectedImages.isEmpty()) {
            Toast.makeText(this, "请输入文字内容或选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String token = sp.getString("token", null);

        if (token == null) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 重置上传状态
        uploadedImageUrls.clear();
        uploadCompletedCount = 0;

        // 有图片则上传图片，无图片则直接发布文字
        if (!selectedImages.isEmpty()) {
            Toast.makeText(this, "正在发布...", Toast.LENGTH_SHORT).show();

            // 显示所有图片的进度条
            for (Uri uri : selectedImages) {
                ProgressBar progressBar = imageProgressMap.get(uri);
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                }
            }

            // 上传所有选中的图片
            for (Uri imageUri : selectedImages) {
                uploadImage(imageUri, token);
            }
        } else {
            // 无图片，直接发布文字内容
            publishDynamic(token);
        }
    }

    // 图片上传方法
    private void uploadImage(Uri imageUri, String token) {
        try {
            // 创建MultipartBody请求体
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",
                            getFileNameFromUri(imageUri),
                            RequestBody.create(MediaType.parse("image/*"),
                                    getFileBytesFromUri(imageUri)))
                    .build();

            // 构建请求
            Request request = new Request.Builder()
                    .url(FILE_UPLOAD_API)  // 文件上传接口地址
                    .addHeader("Authorization", "Bearer " + token)
                    .post(requestBody)
                    .build();

            // 发送请求
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
                    runOnUiThread(() -> {
                        String errorMsg = "上传失败: " + e.getMessage();
                        Log.e("UploadError", errorMsg, e);
                        Toast.makeText(ReleaseDynamicActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                        // 隐藏当前图片的进度条
                        ProgressBar progressBar = imageProgressMap.get(imageUri);
                        if (progressBar != null) {
                            progressBar.setVisibility(View.GONE);
                        }
                    });
                    uploadCompletedCount++;
                    checkUploadCompletion(token);
                }

                @Override
                public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
                    // 使用try-with-resources确保ResponseBody自动关闭
                    try (ResponseBody body = response.body()) {
                        runOnUiThread(() -> {
                            // 隐藏当前图片的进度条
                            ProgressBar progressBar = imageProgressMap.get(imageUri);
                            if (progressBar != null) {
                                progressBar.setVisibility(View.GONE);
                            }
                        });

                        if (response.isSuccessful() && body != null) {
                            String responseBody = body.string();
                            Log.d("图片上传响应", responseBody);

                            try {
                                // 解析响应获取图片URL
                                JSONObject jsonObject = new JSONObject(responseBody);
                                if (jsonObject.getInt("code") == 200) {
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String imageUrl = data.getString("url");
                                    uploadedImageUrls.add(imageUrl);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    uploadCompletedCount++;
                    checkUploadCompletion(token);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(() -> {
                Toast.makeText(this, "上传准备失败", Toast.LENGTH_SHORT).show();
                // 隐藏当前图片的进度条
                ProgressBar progressBar = imageProgressMap.get(imageUri);
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            });
        }
    }

    // 检查所有图片是否上传完成
    private void checkUploadCompletion(String token) {
        if (uploadCompletedCount == selectedImages.size()) {
            runOnUiThread(() -> {
                if (uploadedImageUrls.size() == selectedImages.size()) {
                    publishDynamic(token);
                } else {
                    if (uploadedImageUrls.isEmpty()) {
                        Toast.makeText(ReleaseDynamicActivity.this, "所有图片上传失败", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ReleaseDynamicActivity.this, "部分图片上传失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    // 发布动态方法
    private void publishDynamic(String token) {
        try {
            // 构建请求JSON
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("textContent", etContent.getText().toString().trim());

            // 添加图片URL数组
            JSONArray imageUrlsArray = new JSONArray();
            for (String url : uploadedImageUrls) {
                imageUrlsArray.put(url);
            }
            jsonObject.put("imageUrls", imageUrlsArray);

            // 构建请求体
            RequestBody body = RequestBody.create(
                    jsonObject.toString(),
                    MediaType.get("application/json; charset=utf-8"));

            // 构建请求
            Request request = new Request.Builder()
                    .url(RELEASE_DYNAMIC_API)  // 动态发布接口地址
                    .post(body)
                    .addHeader("Authorization", "Bearer " + token)
                    .build();

            // 创建新的OkHttpClient实例以避免取消问题
            OkHttpClient publishClient = new OkHttpClient();
            publishClient.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
                    runOnUiThread(() -> {
                        Toast.makeText(ReleaseDynamicActivity.this, "发布失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
                    try (ResponseBody body = response.body()) {
                        runOnUiThread(() -> {
                            if (response.isSuccessful()) {
                                Toast.makeText(ReleaseDynamicActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Toast.makeText(ReleaseDynamicActivity.this, "发布失败，请稍后重试", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
            runOnUiThread(() -> {
                Toast.makeText(ReleaseDynamicActivity.this, "数据格式错误", Toast.LENGTH_SHORT).show();
            });
        }
    }

    // 从Uri获取文件名
    private String getFileNameFromUri(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (columnIndex != -1) {  // 确保列索引有效
                        result = cursor.getString(columnIndex);
                    }
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

    // 从Uri获取文件字节
    private byte[] getFileBytesFromUri(Uri uri) throws IOException {
        try (InputStream inputStream = getContentResolver().openInputStream(uri);
             ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                byteBuffer.write(buffer, 0, len);
            }
            return byteBuffer.toByteArray();
        }
    }

    private int dpToPx(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
    }

    @Override
    public void onImageClose() {
        rvZoomedImages.setVisibility(View.GONE);
    }
}